<template>
  <div class="app-container">
    <my-tree-selector-query
      ref="regionTree"
      title="部署区域"
      :current-node-key="this.filter.data.regionId"
      :default-expanded-keys="[this.filter.data.regionId]"
      :options="regionDataOptions"
      :treeProps="{ children: 'children',label: 'name'}"
      @click-node="handleNodeClick"
    />
    <div class="right-wrap">
      <u-page-config
        :filter-array="filterArray"
        v-model="filter"
        :actionBtn="actionBtn"
        label-width="124px"
        :getList="getList"
        :tableData="tableData"
        :tableColumn="tableColumn"
        :total="total"
        :loading="loading"
        showSelection
        @handleSelectionChange="handleSelectionChange"
        @addWorkOrder="addWorkOrder"
        @addFixRecord="addFixRecord"
        @pullLog="pullLog"
        @restart="restart"
        @shutdown="shutdown"
        @rowDetail="rowDetail"
      >
        <template #groupId="{item}">
          <treeselect
            v-model="filter.data.groupId"
            :options="groupOptions"
            :normalizer="normalizer"
            :show-count="true"
            placeholder="选择分组"
            style="width: 240px"
            noOptionsText="暂无选项"
            noResultsText="没有匹配的搜索结果"
          />
        </template>

        <div class="head-card-wrap" slot="head">
          <div class="card-item" v-for="item in cardList" :key="item.key" @click="handleFilterDeviceStatus(item.status)">
            <div class="name">
              <div class="circle" :style="{'background': item.color}"/>
              {{ item.name }}
            </div>
            <div class="value">{{ deviceNumData[item.key] || 0 }}<span>台</span></div>
          </div>
        </div>

        <template #btn="{row, item}">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="rowDetail(row)"
            v-hasPermi="['operationAndMonitoring:deviceMonitoring:detail']"
          >详细信息
          </el-button>

          <el-dropdown @command="(command) => handleCommand(command, row)" trigger="click">
            <span class="el-dropdown-link">更多</span>
            <el-dropdown-menu slot="dropdown">
              <template v-for="item in actionBtn">
                <el-dropdown-item
                  :command="item.emit"
                  :icon="item.icon"
                  v-hasPermi="[item.permissions]"
                >{{ item.text }}
                </el-dropdown-item>
              </template>
            </el-dropdown-menu>
          </el-dropdown>
        </template>

        <template #deviceStatus="scope">
          <dict-tag
            :options="dict.type.device_status"
            :value="scope.row.deviceStatus"
          />
        </template>
      </u-page-config>
    </div>

    <add-work-order-dialog
      v-model="addWorkOrderDialogVisible"
      :device-data="checkedDeviceList[0]"
    />

    <add-fix-records-dialog
      v-model="addFixRecordDialogVisible"
      :device-data="checkedDeviceList[0]"
    />

    <remote-command-dialog
      v-model="remoteCommandDialogVisible"
      :device-data-list="checkedDeviceList"
      :remoteCommandType="remoteCommandType"
    />

  </div>
</template>

<script>
import MyTreeSelectorQuery from "@/views/components/myTreeSelectorQuery";
import table from "@/mixin/uTable";
import UPageConfig from "@/components/uPageConfig/index";
import UForm from "@/components/uForm/index";
import Treeselect from "@riophae/vue-treeselect";
import AddWorkOrderDialog from '../workerOrder/components/addWorkOrderDialog'
import AddFixRecordsDialog from '../fixRecords/components/addFixRecordsDialog'
import RemoteCommandDialog from './components/remoteCommandDialog'
import {reqGetCountDeploymentStatus, listManager} from "@/api/operationAndMonitoring/deviceMonitoring";
import {listGroup} from "@/api/device/group";
import {handleTree} from "@/utils/ruoyi";

export default {
  name: "DeviceMonitoring",
  mixins: [table],
  dicts: ['device_status'],
  components: {
    UPageConfig,
    MyTreeSelectorQuery,
    Treeselect,
    AddWorkOrderDialog,
    AddFixRecordsDialog,
    RemoteCommandDialog
  },
  data() {
    return {
      filter: {
        pageSize: 10,
        pageNum: 1,
        data: {
          deviceStatus: undefined
        }
      },
      filterArray: [
        {label: "部署名称", key: "deploymentName", type: "input"},
        {label: "设备ID", key: "deviceId", type: "input"},
        {label: "部署分组", key: "groupId", type: "slot", slot: 'groupId'},
        {label: "设备状态", key: "deviceStatus", type: "select", options: [],},
        {
          label: "设备品牌", key: "brandCode", type: "select", options: [],
          props: {value: 'code', label: 'name'}
        },
      ],
      tableColumn: [
        {label: "设备ID", prop: "deviceId"},
        {label: "设备部署名称", prop: "deploymentName"},
        {label: "部署区域", prop: "ancestorsName"},
        {label: "部署分组", prop: "groupName"},
        {label: "型号", prop: "deviceName"},
        // {label: "中间件版本", prop: "middlewareVersion"},
        {label: "状态", prop: "orderStatus", type: 'slot', slot: 'deviceStatus'},
        {label: "操作", type: "slot", attr: {width: 120}, slot: 'btn'}
      ],
      actionBtn: [
        {
          type: 'primary',
          text: '添加工单',
          icon: 'el-icon-folder-add',
          emit: 'addWorkOrder',
          permissions: 'operationAndMonitoring:deviceMonitoring:addWorkOrder',
          disabledRule: () => this.ids.length !== 1
        },
        {
          type: 'success',
          text: '添加维修记录',
          icon: 'el-icon-key',
          emit: 'addFixRecord',
          permissions: 'operationAndMonitoring:deviceMonitoring:addFixRecord',
          disabledRule: () => this.ids.length !== 1
        },
        {
          type: 'warning',
          text: '拉取客户端日志',
          icon: 'el-icon-document',
          emit: 'pullLog',
          permissions: 'operationAndMonitoring:deviceMonitoring:pullLog',
          disabledRule: () => this.ids.length !== 1
        },
        {
          type: 'info',
          text: '关机',
          icon: 'el-icon-switch-button',
          emit: 'shutdown',
          permissions: 'operationAndMonitoring:deviceMonitoring:shutdown',
          disabledRule: () => this.ids.length === 0
        },
        {
          type: 'danger',
          text: '重启',
          icon: 'el-icon-refresh-left',
          emit: 'restart',
          permissions: 'operationAndMonitoring:deviceMonitoring:restart',
          disabledRule: () => this.ids.length === 0
        },
      ],
      // 表单默认必填参数 重置表单时需要用到
      defaultForm: {
        deviceId: '',
        deploymentName: '',
        deploymentCode: '',
        operationUserCode: '',
        message: '',
        image: '',
        reportName: '',
        reportPhone: '',
      },
      formArray: [
        {
          label: "设备ID：", key: "deviceId", col: 24, slot: "deviceId",
          rule: {required: true, message: '设备ID不能为空！', trigger: 'blur'},
        },
        {label: "部署名称：", key: "deploymentName", col: 24, type: "input", attr: {disabled: true}},
        {
          label: "运维人员：", key: "operationUserCode", col: 24, type: "select", options: [],
          rule: {required: true, message: '运维人员不能为空！', trigger: 'change'},
        },
        {
          label: "问题描述：", key: "message", col: 24, type: "input",
          rule: {required: true, message: '问题描述不能为空！', trigger: 'blur'},
        },
        {label: "照片：", key: "image", col: 24, slot: "image"},
        {
          label: "报障人联系电话：", key: "reportName", col: 24, type: "input",
          rule: {required: true, message: '报障人联系电话不能为空！', trigger: 'blur'},
        },
        {
          label: "报障人姓名：", key: "reportPhone", col: 24, type: "input",
          rule: {required: true, message: '报障人姓名不能为空！', trigger: 'blur'},
        },
      ],
      // 查看详情表单配置
      detailArray: [
        {
          label: "设备ID：", key: "deviceId", col: 24, type: "text",
        },
        {label: "部署名称：", key: "deploymentName", col: 24, type: "text", placeholder: ' '},
        {
          label: "运维人员：", key: "operationUserCode", col: 24, type: "select", options: [],
        },
        {label: "问题描述：", key: "message", col: 24, type: "text", attr: {resize: 'none'}},
        {label: "照片：", key: "image", col: 24, type: "img"},
        {
          label: "报障人联系电话：", key: "reportPhone", col: 24, type: "text",
        },
        {
          label: "报障人姓名：", key: "reportName", col: 24, type: "text",
        },
      ],
      cardList: [
        {name: '符合条件设备总数', key: 'total', color: 'transparent'},
        {name: '其中正常设备', key: 'normal', status: '1', color: '#13ce66'},
        {name: '其中异常设备', key: 'error', status: '3', color: '#ffba00'},
        {name: '其中离线设备', key: 'offline', status: '2', color: '#f80f02'},
        {name: '其中已关机设备', key: 'poweroff', status: '5', color: '#c1c1c1'},
      ],
      // 添加工单弹窗
      addWorkOrderDialogVisible: false,
      // 添加维修记录弹窗
      addFixRecordDialogVisible: false,
      // 分组选项
      groupOptions: [],
      // 各种设备状态数量
      deviceNumData: {},
      // 拉取日志弹窗
      remoteCommandDialogVisible: false,
      remoteCommandType: '',
      // 当前勾选中的数据
      checkedDeviceList: []
    }
  },
  computed: {
    //默认显示省份ID
    provinceIdConfig() {
      return this.$store.state.app.provinceIdConfig
    },
    // 所有地区树形数据
    regionDataOptions() {
      return this.$store.state.device.regionDataOptions;
    },
    //有效的品牌，用于下拉列表
    brands() {
      return this.$store.state.device.brands || []
    },
  },
  methods: {
    // 点击卡片自动选择筛选状态
    handleFilterDeviceStatus(deviceStatus){
      // 清空选项
      // Object.keys(this.filter.data).forEach(key => {
      //   if(key !== 'regionId'){
      //     this.filter.data[key] = undefined
      //   }
      // })
      this.filter.data.deviceStatus = deviceStatus;
      this.getList()
    },
    remoteCommand(row, type) {
      this.setForm(row);
      this.remoteCommandType = type;
      this.remoteCommandDialogVisible = true;
    },
    // 重启指令
    restart(row) {
      // type参考RemoteCommandDialog组件里面的字典
      this.remoteCommand(row, 'restart')
    },
    // 拉取日志指令
    pullLog(row) {
      // type参考RemoteCommandDialog组件里面字典
      this.remoteCommand(row, 'pullLog')
    },
    // 关机指令
    async shutdown(row) {
      // type参考RemoteCommandDialog组件里面的字典
      this.remoteCommand(row, 'shutdown')
    },
    // 添加维修记录
    addFixRecord(row) {
      this.setForm(row)
      this.addFixRecordDialogVisible = true;
    },
    // 添加工单
    addWorkOrder(row) {
      this.setForm(row)
      this.addWorkOrderDialogVisible = true;
    },
    // 设置当前选择项的表单值
    setForm(row) {
      if (row && row.id) {
        this.checkedDeviceList = [row]
      } else {
        this.checkedDeviceList = this.tableData.filter(item => this.ids.includes(item.id ));
      }
    },
    // 获取各种状态设备数量
    async getCountDeploymentStatus() {
      try {
        const res = await reqGetCountDeploymentStatus({
          ...this.filter.data
        });
        this.deviceNumData = res.data;
      } catch (err) {
        console.log("reqGetCountDeploymentStatus 接口数据异常", err)
      }
    },
    // 下拉按钮
    handleCommand(command, row) {
      try {
        this[command](row);
      } catch (e) {
        console.log(`找不到调用的方法this.${command}`)
      }
    },
    /** 转换区域树形图数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
    // 点击区域节点
    getChildrenRegion(id, options) {
      //是否还没找到，继续循环
      let going = true;
      let result = []
      let walker = (id, array) => {
        array.forEach(item => {
          if (!going) return;
          if (item['id'] === id) {
            going = false;
            result = [item];
          } else if (item['children']) {
            walker(id, item['children']);
          }
        });
      }
      walker(id, options)
      return result
    },
    /** 查询区域包含的分组管理列表 */
    getRegionGroup(regionId) {
      this.loading = true;
      listGroup({regionId}).then(res => {
        this.groupOptions = handleTree(res.rows, "id");
      }).finally(() => {
        this.loading = false;
      });
    },
    handleNodeClick(data) {
      this.filter.data.regionId = data.id;
      // 清空选择的分组
      this.getRegionGroup(data.id)
      this.getList();
    },
    // 表单提交接口相关配置
    formSubmitFunConfig() {
      return {
        addFunc: () => {
        },
        modifyFunc: () => {
        },
        pk: 'id',
        options: {
          ...this.form
        },
        cbFunc: () => {
          this.visible = false
        }
      }
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      console.log(selection,'selection')
      this.ids = selection.map(item => item.id);
    },
    /** 查询工单列表 */
    getList() {
      // 如果点击了重置按钮，regionId被清空后，自动赋值为默认省份id
      if(!this.filter.data.regionId){
        this.filter.data.regionId = this.provinceIdConfig;
        this.$refs.regionTree.$refs.tree.setCurrentKey(this.provinceIdConfig);
      }
      // 获取列表
      this.getInit(listManager, {})
      // 获取各种状态设备数量
      this.getCountDeploymentStatus();
    },
    /** 详细按钮操作 */
    rowDetail(row) {
      console.log(row, "row详情")
      this.$router.push({
        name: 'DeviceMonitoringDetail',
        query: {
          deviceId: row.deviceId,
          ipAddress: row.ipAddress
        }
      })
    },
    /** 返回设备部署页面 */
    goBack() {
      this.$router.go(-1);
    },
  },
  watch: {
    'dict.type.device_status': {
      handler(newValue) {
        // 设置设备状态选项数据
        try {
          this.filterArray.find(item => item.key === 'deviceStatus').options = newValue;
        } catch (e) {
          console.log("找不到对应表单项", e)
        }
      },
    },
    brands: {
      immediate: true,
      handler(newValue) {
        // 设置品牌选项数据
        try {
          this.filterArray.find(item => item.key === 'brandCode').options = newValue;
        } catch (e) {
          console.log("找不到对应表单项", e)
        }
      }
    },
  },
  created() {
    // 设置默认选择区域
    this.filter.data.regionId = this.provinceIdConfig;
    // 获取分组
    this.getRegionGroup(this.provinceIdConfig);
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  display: flex;
  min-height: inherit;

  .right-wrap {
    flex: 1;
    width: 100%;
    height: 100%;
    overflow: hidden;

    .head-card-wrap {
      display: flex;
      width: 100%;
      min-width: 850px;
      margin-bottom: 20px;
      border: 1px solid #409eff;
      border-radius: 2px;
      background: #fff;
      box-shadow: 0 2px 8px -2px rgb(0, 0, 0, 10%);

      .card-item {
        position: relative;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 75px;
        width: 25%;
        font-size: 16px;
        cursor: pointer;

        .name {
          display: flex;
          align-items: center;

          .circle {
            width: 12px;
            height: 12px;
            margin-right: 5px;
            border-radius: 50%;
            background: greenyellow;
          }
        }

        .value {
          margin-top: 8px;
          font-size: 20px;

          span {
            font-size: 18px;
          }
        }

        &:last-child {
          &::after {
            width: 0;
          }
        }

        &::after {
          position: absolute;
          content: '';
          right: 0;
          top: 50%;
          width: 1px;
          height: 60%;
          background: #409eff;
          transform: translateY(-50%);
        }
      }
    }
  }

}
</style>
